<template>
  <van-field
    v-model="select"
    is-link
    readonly
    :name="name"
    :label="label"
    placeholder="请选择日期"
    :rules="rules"
    @click="show = true"
  />
  <!-- <van-calendar v-model:show="show" @confirm="confirm" /> -->
  <van-popup v-model:show="show" position="bottom" teleport="body">
    <van-datetime-picker
      :type="type"
      v-model="currentDate"
      :min-date="minDate"
      :max-date="maxDate"
      @confirm="confirm"
      @cancel="show = false"
    />
  </van-popup>
</template>

<script lang="ts">
import { defineComponent,reactive,toRefs ,watch,nextTick,PropType} from 'vue'
const dealTimeNumber = function(num){
  if(num >= 10){
    return num;
  }else{
    return '0'+num;
  }
}
export default defineComponent({
  name:'tDate',
  emits:['update:modelValue','select'],
  props:{
    modelValue: String,
    rules:{
      type:Array,
      default:[]
    },
    pickerType:{
      type:String,
      default:'datetime'
    },
    name:String,
    label:String
  },
  setup (props,{emit}) {
    const data = reactive({
      show:false,
      select:'',
      type: props.pickerType,
      currentDate:new Date(),
      minDate: new Date(2020, 0, 1),
      maxDate:new Date()
    })
    const update = function(modelValue){
      data.select = modelValue||''
      data.currentDate = data.select?new Date(data.select):new Date();
    }
    watch(()=>props.modelValue,(data,prev)=>{
      update(data)
    })
    watch(()=>props.pickerType,(res,prev)=>{
      data.type = res;
      // update(data)
    })
    nextTick(()=>{
      update(props.modelValue);
    })
    return {
      ...toRefs(data),
      confirm(date){
        let value = `${date.getFullYear()}-${dealTimeNumber(date.getMonth() + 1)}-${dealTimeNumber(date.getDate())} ${dealTimeNumber(date.getHours())}:${dealTimeNumber(date.getMinutes())}:${dealTimeNumber(date.getSeconds())}`;
        data.select = value;
        emit('update:modelValue',value)
        emit('select',data);
        data.show = false;
      }
    }
  }
})
</script>